package cn.maka.web.servlet;

import cn.maka.util.DownLoadUtils;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

@WebServlet("/downloadServlet")
public class DownloadServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String filename = request.getParameter("filename");

        ServletContext servletContext = this.getServletContext();
        String realPath = servletContext.getRealPath("/img/" + filename);

        //使用字节流加载文件进内存
        FileInputStream fileInputStream = new FileInputStream(realPath);

        String mimeType = servletContext.getMimeType(filename);
        response.setHeader("content-type",mimeType);

        String agent = request.getHeader("user-agent");
        filename = DownLoadUtils.getFileName(agent, filename);
        response.setHeader("content-disposition","attachment;filename="+filename);

        ServletOutputStream outputStream = response.getOutputStream();
        BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);

        /*byte[] buff = new byte[1024];
        int len = 0;
        while ((len=fileInputStream.read(buff)) != -1){
            outputStream.write(buff,0,len);
        }*/

        int len = 0;
        while ((len = bufferedInputStream.read()) != -1) {
            outputStream.write(len);
        }

        bufferedInputStream.close();
        fileInputStream.close();




    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }
}
